from __future__ import division

from numpy import array, round
from smooth import *

def randomrange(base, upper):
	"""
	return a pseudo-random floating point number between base and upper.
	base should be lesser the upper, no checks performed.
	"""
	return random.random() * (upper-base) + base


def ecg(L, smooth_flag=True):
	"""
	return a picewise linear electocardiogram wave of lenght L
	smooth_flag add Savitzky-Golay FIR filter.
	euristic implementations based on 
	ecg.m - R. Losada 1988-2002 The MathWorks, Inc.
	"""
	a0 = array( [0,1,40,1,0,-34,118,-99,0,2,21,2,0,0,0] )
	d0 = array( [0,27,59,91,131,141,163,185,195,275,307,339,357,390,440] )

	a0 = array([i+randomrange(1,6) if i!=0
		    else 0
		    for i in a0]) 
	a0[6] = 300


	a = a0 / max(a0)
	d = (d0 * L / d0[-1]).round()
	d[14] = L

	x = array( [0.0 for i in range(L)] )

	for i in range(14):
		s = int( d[i]+1 ) 
		e = int( d[i+1]+1 )
		m =  array([ j for j in range(s, e) ])
		slope = ( a[i+1] - a[i] ) / ( d[i+1] - d[i] )
		try:	
			x[ m+1 ] = a[i] + slope * (m - d[i])
		except IndexError: pass

	#x = array([randomrange(1,1.2) for i in range(len(x))]) * x
		
	c = calc_coeff(5, 0)
	if smooth_flag:return smooth(x, c)
	else: return x

if __name__ == "__main__":
	#print ecg(500)
	k = 150
	import matplotlib.pyplot as plt
	plt.plot(ecg(k))
	plt.plot(ecg(k, False), 'r')
	plt.show()
	print len(ecg(k))
